package com.ly.oss.service.weixin;

import java.util.Date;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;

import com.ly.oss.comm.Delete;
import com.ly.oss.comm.MyPage;
import com.ly.oss.entity.WeixinPublic;
import com.ly.oss.repository.WeixinPublicDao;
import com.ly.oss.service.account.ShiroDbRealm.ShiroUser;

/**
 * 
 * 
 * @author Peter
 */
// Spring Service Bean的标识.
@Component
public class WeixinPublicService {

	private static Logger logger = LoggerFactory.getLogger(WeixinPublicService.class);

	@Autowired
	private WeixinPublicDao weixinPublicDao;
	

	public WeixinPublic getById(Long id) {
		return weixinPublicDao.getById(id);
	}

	public List<WeixinPublic> getAll() {
		return weixinPublicDao.getAll();
	}

	/**
	 * 分页查询
	 * 
	 * @param overtime
	 * @param pageStart
	 * @param pageSize
	 * @return
	 */
	public MyPage<WeixinPublic> searchPage(WeixinPublic weixinPublic, int currentPage, int pageSize) {
		MyPage<WeixinPublic> myPage = new MyPage<WeixinPublic>();

		Long count = weixinPublicDao.searchCount(weixinPublic);

		int pageStart = (currentPage - 1) < 0 ? 0 : (currentPage - 1) * pageSize;
		List<WeixinPublic> list = weixinPublicDao.searchPage(weixinPublic, pageStart, pageSize);

		myPage.setCount(count);
		myPage.setContent(list);

		return myPage;
	}

	public void save(WeixinPublic weixinPublic) {
		weixinPublicDao.save(weixinPublic);
	}

	public void update(WeixinPublic weixinPublic) {
		weixinPublic.setUpdateDate(new Date());
		weixinPublic.setUpdateUserUid(getCurrentUserUid());
		
		if(weixinPublic.getId()==null){
			weixinPublic.setCreateDate(new Date());
			weixinPublic.setDeleted(Delete.Enabled);
			weixinPublic.setCreateUserUid(getCurrentUserUid());
			
			weixinPublicDao.save(weixinPublic);
		}else{
			
			weixinPublicDao.update(weixinPublic);
		}
	}

	/**
	 * 软删除
	 */
	public void delete(Long id) {
		weixinPublicDao.delete(id);
	}
	
	/**
	 * 取出Shiro中的当前用户Id.
	 */
	private String getCurrentUserUid() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user.getUid();
	}
}
